--连接redis
local redis = require "resty.redis"
local red = redis:new()
--local ok, err = red:connect("192.168.1.32", 19000)
local ok, err = red:connect("192.168.1.43", 6379)
-- local ok, err = red:connect("127.0.0.1", 6379)
red:auth("zhugeredis")
red:set_timeout(1000) -- 1 sec

--获取参数
local request_method = ngx.var.request_method  
local args = nil  
local url = nil
local passwd = nil
local content = nil  
local checkContent = nil
local baseUrl = nil
local ipCount = nil
local urlCount = nil


--获取参数的值  
if "GET" == request_method then  
    args = ngx.req.get_uri_args()  
elseif "POST" == request_method then  
    ngx.req.read_body()  
    args = ngx.req.get_post_args()  
end  
url = args["url"]  
passwd = args["passwrod"]

if url == "" or url == nil or passwd ~= "proxy.zhugefang"
then
    ngx.say("别闹~~")
   return
end

--匿名函数  判断内容是否存在
checkContent = function(text) 
	if type(text) == "userdata" or text == "" or text == nil 
	then
	    return false
	end
        return true
end

baseUrl = ngx.encode_base64(url)
--获取内容
content = red:get(baseUrl)

--检查内容是否存在
if checkContent(content) == true then
    ngx.say(ngx.decode_base64(content))
    return
end

--获取内容
ipCount = red:scard("proxy_usable_ip_2")
urlCount = red:llen("proxy_url_list")

if ipCount - urlCount < 0
then
    ngx.say("ip insufficient")
    return
end

--检查内容是否 ""
if content == '' then
    red:del(baseUrl)
end
--内容不存在，将种子放到池子中
red:rpush("proxy_url_list", url)
--循环等待内容的产出，最多等待20秒
for i= 1, 60 do
    os.execute("sleep 1")
    content = red:get(baseUrl)
    if checkContent(content) == true then
        ngx.say(ngx.decode_base64(content))
        return
    end
    --检查内容是否 ""
    if content == '' then
        red:del(baseUrl)
    end
end



ngx.say("")
return
